const Router = require("@koa/router");
const router = new Router();
const jwt = require("jsonwebtoken");
const {Sequelize, DataTypes, where} = require("sequelize");
// 验证用户身份的中间件
const authenticateUser = async (ctx, next) => {
  const token = ctx.headers.authorization;

  if (!token) {
    ctx.status = 401;
    ctx.body = {error: "未提供身份验证令牌。"};
    return;
  }

  // 解码 base64 编码的 token
  const decodedToken = Buffer.from(token, "base64").toString("utf-8");

  jwt.verify(decodedToken, "token", (err, decoded) => {
    if (err) {
      ctx.status = 401;
      ctx.body = {error: "无效的身份验证令牌。"};
      return;
    }

    ctx.state.userId = decoded.userId;
  });

  await next();
};

// 获取员工列表
router.post("/getemployeslist", authenticateUser, async (ctx) => {
  try {
    // 从请求体中获取条件查询参数和页码信息
    const {
      name,
      job_number,
      sex,
      position,
      wokerstate,
      page = 1,
    } = ctx.request.body;

    // 构建查询条件对象
    const whereClause = {};

    // 添加每个条件的 LIKE 查询
    if (name) {
      whereClause.name = {[Sequelize.Op.like]: `%${name}%`};
    }
    if (job_number) {
      whereClause.job_number = job_number;
    }
    if (sex) {
      whereClause.sex = sex;
    }
    if (position) {
      whereClause.position = position;
    }
    if (wokerstate) {
      whereClause.wokerstate = wokerstate;
    }

    // 计算查询偏移量
    const offset = (page - 1) * 10;

    // 查询符合条件的员工列表，并按 createdAt 时间倒序排列
    const UserList = await ctx.state.Employee.findAll({
      where: whereClause,
      order: [["createdAt", "DESC"]], // 按 createdAt 时间倒序排列
      limit: 10,
      offset: offset,
    });

    // 查询数据总数
    const total = await ctx.state.Employee.count({
      where: whereClause,
    });

    ctx.status = 200;
    ctx.body = {UserList, total};
  } catch (error) {
    console.error("Error fetching menu:", error);
    ctx.status = 500;
    ctx.body = {error: "获取员工列表时发生错误。"};
  }
});

// 添加员工项
router.post("/add", authenticateUser, async (ctx) => {
  try {
    // 获取请求体中的菜单信息
    const { id, name, job_number, sex, position, wokerstate } = ctx.request.body;

    // 检查请求体中各项是否为空
   
    if (!name) {
      ctx.status = 201;
      ctx.body = { message: "员工姓名不能为空。" };
      return;
    }

    if (!job_number) {
      ctx.status = 201;
      ctx.body = { message: "员工工号不能为空。" };
      return;
    }

    if (!sex) {
      ctx.status = 201;
      ctx.body = { message: "员工性别不能为空。" };
      return;
    }

    if (!position) {
      ctx.status = 201;
      ctx.body = { message: "员工职位不能为空。" };
      return;
    }

    if (!wokerstate) {
      ctx.status = 201;
      ctx.body = { message: "员工状态不能为空。" };
      return;
    }

    // 检查是否存在同名员工
    const existingEmployee = await ctx.state.Employee.findOne({
      where: { job_number },
    });

    // 如果存在同名员工，则提示不能添加
    if (existingEmployee) {
      if (id) {
        await update(ctx);
      }
      return;
    }

    // 创建员工项
    const newEmployee = await ctx.state.Employee.create({
      name,
      job_number,
      sex,
      position,
      wokerstate,
    });

    ctx.status = 200;
    ctx.body = { message: "新员工添加成功。", employee: newEmployee };
  } catch (error) {
    console.error("Error adding employee:", error);
    ctx.status = 500;
    ctx.body = { error: "添加员工项时发生错误。" };
  }
});


async function update(ctx) {
  try {
    // 查找要修改的菜单项
    const {name, job_number, sex, position, wokerstate} = ctx.request.body;
    const userId = ctx.request.body.id;

    const employeeToUpdate = await ctx.state.Employee.findOne({
      where: {
        id: userId, // 排除当前菜单项的ID
      },
    });

    if (!employeeToUpdate) {
      ctx.status = 404;
      ctx.body = {error: "未找到要修改的员工数据。"};
      return;
    }

    // 检查是否存在其他具有相同员工编号的员工
    const existingemployee = await ctx.state.Employee.findOne({
      where: {
        job_number,
        id: {[Sequelize.Op.not]: userId}, // 排除当前员工ID
      },
    });

    if (existingemployee) {
      ctx.status = 400;
      ctx.body = {error: "已存在相同名的员工，请选择其他名字。"};
      return;
    }

    // 修改菜单项
    await employeeToUpdate.update({
      name,
      job_number,
      sex,
      position,
      wokerstate,
    });

    ctx.status = 200;
    ctx.body = {message: "员工信息修改成功。", user: employeeToUpdate};
  } catch (error) {
    console.error("Error editing menu item:", error);
    ctx.status = 500;
    ctx.body = {error: "修改员工信息时发生错误。"};
  }
}

// 修改员工项
router.post("/update", authenticateUser, async (ctx) => {
  try {
    // 查找要修改的菜单项
    const {id, name, job_number, sex, position, wokerstate} = ctx.request.body;
    const userId = ctx.request.body.id;

    const employeeToUpdate = await ctx.state.Employee.findOne({
      where: {
        id: userId, // 排除当前菜单项的ID
      },
    });

    if (!employeeToUpdate) {
      ctx.status = 404;
      ctx.body = {error: "未找到要修改的员工数据。"};
      return;
    }

    // 检查是否存在其他具有相同菜名的菜单项
    const existingemployee = await ctx.state.Employee.findOne({
      where: {
        name,
        id: {[Sequelize.Op.not]: userId}, // 排除当前员工ID
      },
    });

    if (existingemployee) {
      ctx.status = 400;
      ctx.body = {error: "已存在相同名的员工，请选择其他名字。"};
      return;
    }

    // 修改菜单项
    await employeeToUpdate.update({
      name,
      job_number,
      sex,
      position,
      wokerstate,
    });

    ctx.status = 200;
    ctx.body = {message: "员工信息修改成功。", menu: menuToUpdate};
  } catch (error) {
    console.error("Error editing menu item:", error);
    ctx.status = 500;
    ctx.body = {error: "修改员工信息时发生错误。"};
  }
});

// 员工工作状态修改
router.post("/workStateUpdate", authenticateUser, async (ctx) => {
  try {
    // 获取请求体中的员工状态信息
    const wokerstate = ctx.request.body.wokerstate;
    const employeeId = ctx.request.body.id;

    // 查找要修改的员工项
    const employeeToUpdate = await ctx.state.Employee.findOne({
      where: {
        id: employeeId, // 排除当前员工的ID
      },
    });

    if (!employeeToUpdate) {
      ctx.status = 404;
      ctx.body = {error: "未找到要修改的员工项。"};
      return;
    }
    console.log(wokerstate);
    // 修改员工状态
    await employeeToUpdate.update({
      workerstate:wokerstate,
    });

    ctx.status = 200;
    ctx.body = {message: "员工状态修改成功。", Employee: employeeToUpdate};
  } catch (error) {
    console.error("Error editing menu item:", error);
    ctx.status = 500;
    ctx.body = {error: "菜单项下架时发生错误。"};
  }
});

// 删除员工
router.post("/delete", authenticateUser, async (ctx) => {
  try {
    const userId = ctx.request.body.id;

    // 查找要删员工项
    const employeeToDelete = await ctx.state.Employee.findByPk(userId);

    // 删除员工项
    await employeeToDelete.destroy();

    ctx.status = 200;
    ctx.body = {message: "员工项删除成功。"};
  } catch (error) {
    console.error("Error deleting menu item:", error);
    ctx.status = 500;
    ctx.body = {error: "删除员工项时发生错误。"};
  }
});

module.exports = router;
